/* (c)2010-2013 Andrea Caltroni (andrea.caltroni@pd.infn.it), INFN (www.infn.it)
 *
 * This file is part of the IGI Survey Portlet (from here on shortened to IGISP).
 * IGISP is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) any 
 * later version.
 *
 * IGISP is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with IGISP. If not, see <http://www.gnu.org/licenses/>.
 */
package it.infn.grid.liferay.survey.modules.admin.controller;

import it.infn.grid.liferay.survey.modules.admin.web.SurveyStatusPropertyEditor;
import it.infn.grid.liferay.survey.modules.admin.web.SurveyValidator;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;

import org.ajm.spring.survey.modules.admin.model.Survey;
import org.ajm.spring.survey.modules.admin.model.SurveyStatus;
import org.ajm.spring.survey.modules.admin.service.SurveyService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

/**
 * The controller for the edit a survey operation on the Survey object.
 * 
 * @author Andrea Caltroni, andrea.caltroni@pd.infn.it, INFN
 */
@RequestMapping(value="VIEW")
@Controller(value="editSurveyController")
public class EditSurveyController {
    
    // ------------------------------------------------------------------------|
    // --- CONSTANTS ----------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // --- CLASS VARIABLES ----------------------------------------------------|
    // ------------------------------------------------------------------------|
    // ------------------------------------------------------------------------|

    static Logger logger = Logger.getLogger(EditSurveyController.class);
    
    // ------------------------------------------------------------------------|
    // --- INSTANCE VARIABLES -------------------------------------------------|
    // ------------------------------------------------------------------------|

    @Autowired
    @Qualifier("surveyService")
    private SurveyService surveyService;
    
    @Autowired
    @Qualifier("surveyValidator")
    private SurveyValidator surveyValidator = new SurveyValidator();
    
    private SimpleDateFormat dateFormat = new SimpleDateFormat(Survey.DATE_PATTERN);
    
    // ------------------------------------------------------------------------|
    // --- CONSTRUCTORS -------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- CLASS METHODS ------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- INSTANCE METHODS ---------------------------------------------------|
    // ------------------------------------------------------------------------|

    /**
     * Setup binder for adding/editing surveys.
     */
    @InitBinder("survey")
    protected void initBinder(PortletRequestDataBinder binder) {
        
        getDateFormat().setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, false));

        binder.registerCustomEditor(SurveyStatus.class, new SurveyStatusPropertyEditor());
        
        //binder.setAllowedFields(new String[] {"name", "description", "status", "expiration","questions"});
    }

    // ------------------------------------------------------------------------|

    @ModelAttribute("survey")
    public Survey getCommandObject(@RequestParam("surveyID") Long surveyId) {
        
        return getSurveyService().findById(surveyId);
    }

    // ------------------------------------------------------------------------|

    /**
     * Edits a survey. Render phase.
     * 
     * @param model 
     * @return The attribute in the model defining the action of editing a survey.
     */
    @RenderMapping(params="action=showEditSurveyForm")
    public String showEditSurveyForm(Model model) {
        
        model.addAttribute("status", Arrays.asList(SurveyStatus.values()));
        model.addAttribute("dateFormatPattern", getDateFormat().toLocalizedPattern().toLowerCase());
        
        return "surveyEdit";
    }

    // ------------------------------------------------------------------------|

    /**
     * Edits a survey. Action phase.
     * 
     * @param request 
     * @param response 
     * @param survey 
     * @param bindingResult 
     * @param sessionStatus 
     */
    @ActionMapping(params="action=editSurvey")
    public void submitEditSurveyForm(ActionRequest request, ActionResponse response,
            @ModelAttribute("survey") Survey survey, BindingResult bindingResult, SessionStatus sessionStatus) {

        getSurveyValidator().validate(survey, bindingResult);
        
        if (!bindingResult.hasErrors()) {
            // set expiration time
            Date timeSetExpiration = survey.getExpiration();
            timeSetExpiration.setTime(timeSetExpiration.getTime() + 86399000L);
            survey.setExpiration(timeSetExpiration);
            
            Survey savedSurvey = surveyService.save(survey);
            response.setRenderParameter("action", "viewSurvey");
            response.setRenderParameter("surveyID", savedSurvey.getId().toString());
        }
        else {
            if (bindingResult.hasFieldErrors("start") && survey.getStart() == null) {
                // TODO we should distinguish here between empty date or errors.
                // in case of errors, page should be reloaded
                Date now = new Date();
                survey.setStart(now);
                // set expiration time
                Date timeSetExpiration = survey.getExpiration();
                timeSetExpiration.setTime(timeSetExpiration.getTime() + 86399000L);
                survey.setExpiration(timeSetExpiration);
                
                Survey savedSurvey = surveyService.save(survey);
                response.setRenderParameter("action", "viewSurvey");
                response.setRenderParameter("surveyID", savedSurvey.getId().toString());
            }
            else {
                if (logger.isDebugEnabled()) {
                    for (ObjectError error: bindingResult.getAllErrors()) {
                        logger.debug("Survey edit form reported [" + error.toString() + "]");
                    }
                }
                response.setRenderParameter("action", "showEditSurveyForm");
                response.setRenderParameter("surveyID", survey.getId().toString());
            }
        }
    }

    // --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --|
    // ---[  GETTERS AND SETTERS  ]--------------------------------------------|
    // --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --|

    /**
     * @param surveyService the surveyService to set
     */
    public void setSurveyService(SurveyService surveyService) {
        
        this.surveyService = surveyService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @return the surveyService
     */
    public SurveyService getSurveyService() {
        
        return surveyService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param surveyValidator the surveyValidator to set
     */
    public void setSurveyValidator(SurveyValidator surveyValidator) {
        
        this.surveyValidator = surveyValidator;
    }

    // ------------------------------------------------------------------------|

    /**
     * @return the surveyValidator
     */
    public SurveyValidator getSurveyValidator() {
        
        return surveyValidator;
    }

    // ------------------------------------------------------------------------|

    /**
     * @return the dateFormat
     */
    public SimpleDateFormat getDateFormat() {
        
        return dateFormat;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param dateFormat the dateFormat to set
     */
    public void setDateFormat(SimpleDateFormat dateFormat) {
        
        this.dateFormat = dateFormat;
    }

    // ------------------------------------------------------------------------|

}